package com.wakyde.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Description: TODO
 * @author: wakyde
 * @date: 2022年05月10日 11:44
 */
public class CookieDemo01 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 解决中文乱码
        req.setCharacterEncoding("utf-8");
//        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        PrintWriter out = resp.getWriter();

        // Cookie
        Cookie[] cookies = req.getCookies();

        // 判断cookie是否存在
        if(cookies != null){
            out.write("你上一次访问的时间是:");
            // 循环cookie里面的内容
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("lastLoginTime")) {
                    // 获取cookie中的值
                    String lastLoginTime = cookie.getValue();
                    Long timeLong = Long.parseLong(lastLoginTime);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//要转换的时间格式
                    Date date;
                    try {
                        date = sdf.parse(sdf.format(timeLong));
                        String date1 = sdf.format(date);
                        out.write(date1);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                if (cookie.getName().equals("name")) {
                    // 获取cookie中的值
                    String name = cookie.getValue();
                    out.write(" " + URLDecoder.decode(name, "utf-8"));
                }
            }
        }else {
            out.write("这是你第一次访问本站");
        }

        // 服务端给客户端响应一个cookie
        Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis() + "");
        Cookie cookie1 = new Cookie("name", URLEncoder.encode("六十多", "utf-8"));
        // Cookie有效期为1天
        cookie.setMaxAge(24*60*60);
        resp.addCookie(cookie);
        resp.addCookie(cookie1);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
